package com.nwpu.ex2_1;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;

/**
 * CodeReturn
 *
 * @author 龙虹宇
 * @version 1.0
 * @date 2023/10/14
 */
@WebServlet("/codeReturn")
public class CodeReturn extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取文件名
        String fileName = "bookCode.jar";
        // 设置响应的Content-type
        response.setContentType("application/jar");
        // 设置响应头：Content-Disposition，告诉浏览器以附件的形式打开这个文件
        // "attachment"：这告诉浏览器将数据作为附件下载，而不是在浏览器中显示。
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        // 获取ServletContext
        ServletContext servletContext = getServletContext();
        // 获取对应资源的输入流
        InputStream is = servletContext.getResourceAsStream(fileName);

        int readLen = 0;
        byte[] bytes = new byte[1024];

        // 获取响应字节输出流
        ServletOutputStream os = response.getOutputStream();
        // 向响应中写入数据
        while((readLen = is.read(bytes)) != -1) {
            os.write(bytes, 0 ,readLen);
        }
        os.flush();
        // 关闭输入流
        is.close();
        // 释放资源（其实不用自己手动释放，因为response会在servlet释放之后自行关闭）
        os.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
